package com.why.util;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.jwt.crypto.sign.InvalidSignatureException;
import org.springframework.security.jwt.crypto.sign.MacSigner;

import java.util.Optional;
import java.util.stream.Stream;

public class JwtUtil {

    /**
     * jwt验签
     */
    private static MacSigner verifier;

    @Value("${gate.ignore.authentication.startWith}")
    private String ignoreUrls = "/oauth";

    public static boolean invalidJwtAccessToken(String authentication) {
        verifier = Optional.ofNullable(verifier).orElse(new MacSigner("123456"));
        //是否无效false表示无效
        boolean invalid = Boolean.FALSE;

        try {
            Jwt jwt =  getJwt( authentication);
            jwt.verifySignature(verifier);
            invalid = Boolean.TRUE;
        } catch (InvalidSignatureException | IllegalArgumentException ex) {
//            log.warn("user token has expired or signature error ");
        }
        return invalid;
    }

    public static Jwt getJwt(String authentication) {
        return JwtHelper.decode(StringUtils.substring(authentication,7));
    }


    public boolean ignoreAuthentication(String url) {
        return Stream.of(this.ignoreUrls.split(",")).anyMatch(ignoreUrl -> url.startsWith(StringUtils.trim(ignoreUrl)));
    }

}
